﻿''' <summary>
''' 每月每日來電統計表
''' </summary>
''' <remarks>
''' Author:huyang
''' Create Date:2008-05-28
''' </remarks>
Public Class frm_CSPrintMonthCountNew


    Implements IDServer.IDServer.IDServer

#Region "Variabled"

#Region "System Variabled Define"


    Public ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp

    Private WithEvents MainForm As Frm_MainForm

    Public Property SelectObject() As Frm_MainForm
        Get
            Return MainForm
        End Get
        Set(ByVal value As Frm_MainForm)
            MainForm = value
        End Set
    End Property

    Public action_help As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp

#End Region

#Region "user variabled define"

    ''' <summary>
    ''' 窗體是否加載
    ''' </summary>
    ''' <remarks></remarks>
    Private fLoadBool As Boolean = False


#End Region

#End Region

#Region "Methods"

#Region "ExecFind"

    Private Sub ExecFind()
        Me.Cursor = Cursors.WaitCursor

        Dim sql As String = ""
        Dim Dtab As New DataTable

        sql = "  Exec [usp_ReportCSMonthNew]   '" & Format(Me.dtp_start_1.Value, "yyyy-MM-dd") & "','" & Format(Me.dtp_end_1.Value, "yyyy-MM-dd") & "' "

        Try

            Dim fDays As Integer = 26

            Dtab = Exec(sql, E_ExecType.DataTable)

            Dtab.Columns.Add("fTotals", GetType(System.Double))
            Dtab.Columns.Add("fDays", GetType(System.Int32))
            Dtab.Columns.Add("fAverage", GetType(System.Double))
            Dtab.Columns("Person").ColumnName = "姓 名 "
            ComputeDataTable(Dtab)


            Dtab.Columns("fTotals").ColumnName = "來電總數"
            Dtab.Columns("fDays").ColumnName = "總天數"
            Dtab.Columns("fAverage").ColumnName = "平均每天處理來電總數"
            Dtab.AcceptChanges()


            Me.DataGridView1.Columns.Clear()
            Me.DataGridView1.DataSource = Dtab
            FullFormatDataGridView(Me.DataGridView1, False, False)
            Me.DataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect
            Me.DataGridView1.AutoResizeColumns(System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells)
            If Me.fLoadBool = True Then
                SetButton(ButtonType.Browse, False)
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            Me.Cursor = Cursors.Default
        End Try

    End Sub

    Private Sub ComputeDataTable(ByRef Dtab As DataTable)

        For Each row As DataRow In Dtab.Rows
            Dim fTotal As Double = 0.0
            Dim fAverage As Double = 0.0
            Dim fDay As Integer = 0
            If Me.TabControl1.SelectedIndex = 0 Then
                fDay = Val(Me.TextBox1.Text)
                If fDay <= 0 Then
                    fDay = 26
                End If
            End If

            For Each col As DataColumn In Dtab.Columns
                If col.ColumnName.Equals("ListenPsn", StringComparison.InvariantCultureIgnoreCase) _
                OrElse col.ColumnName.Equals("姓名", StringComparison.InvariantCultureIgnoreCase) _
                OrElse col.ColumnName.Equals("姓 名 ", StringComparison.InvariantCultureIgnoreCase) Then

                Else
                    row(col.ColumnName) = IIf(Val(row(col.ColumnName).ToString) > 0, Val(row(col.ColumnName).ToString), System.DBNull.Value)

                    fTotal += Val(row(col.ColumnName) & "")
                    If Me.TabControl1.SelectedIndex = 1 Then
                        If Val(row(col.ColumnName) & "") > 0 Then
                            fDay += 1
                        End If
                    End If
                End If
            Next
            row("fTotals") = fTotal
            row("fDays") = fDay
            If fDay > 0 Then
                row("fAverage") = (fTotal / fDay).ToString("0.0000")
            End If
        Next

    End Sub

    Private Sub ExecFind_2()
        Me.Cursor = Cursors.WaitCursor
        Dim sql As String = ""
        sql = "  Exec   [usp_PrintComplainMonthNew] '" & Format(Me.dtp_start_2.Value, "yyyy-MM-dd") & "','" & Format(Me.dtp_end_2.Value, "yyyy-MM-dd") & "','" & Me.cbxfLevel.Text.Trim & "' "
        Dim Dtab As New DataTable
        Try

            Dtab = Exec(sql, E_ExecType.DataTable)
            Dtab.Columns.Add("fTotals", GetType(System.Double))
            Dtab.Columns.Add("fDays", GetType(System.Int32))
            Dtab.Columns.Add("fAverage", GetType(System.Double))
            ComputeDataTable(Dtab)
            Dtab.AcceptChanges()

            Me.DataGridView2.Columns.Clear()
            Me.DataGridView2.DataSource = Dtab
            BindDataGridViewCaption_1(Me.DataGridView2, Me.ReturnCaption(1))
            FullFormatDataGridView(Me.DataGridView2, False, False)
            Me.DataGridView2.SelectionMode = DataGridViewSelectionMode.CellSelect
            Me.DataGridView2.AutoResizeColumns(System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells)
            If Me.fLoadBool = True Then
                SetButton(ButtonType.Browse, False)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Public Function ReturnCaption(ByVal Index) As Hashtable

        Dim Hash As New Hashtable
        Select Case Index
            Case 1
                Hash.Add("ListenPsn", "姓名")
                Hash.Add("fTotals", "投訴總數")
                Hash.Add("fDays", "總天數")
                Hash.Add("fAverage", "平均每天處理投訴總數")
        End Select
        Return Hash
    End Function

#End Region

#Region "SetEnabled"

    ''' <summary>
    ''' 設置按鈕狀態


    ''' </summary>
    ''' <param name="type">操作類型</param>
    ''' <param name="IsFind">是否是流覽</param>
    ''' <remarks></remarks>
    Private Sub SetButton(ByVal type As ButtonType, ByVal IsFind As Boolean)
        Try

            Select Case type
                Case ButtonType.Add
                    With MainForm
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = False
                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = True
                        .ToolStripCancel.Enabled = True
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

                Case ButtonType.Browse
                    With MainForm
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = IsFind
                        .ToolStripDelete.Enabled = IsFind
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = IsFind
                        .ToolStripLast.Enabled = IsFind
                        .ToolStripNext.Enabled = IsFind
                        .ToolStripPrivous.Enabled = IsFind
                        .ToolStripExport.Enabled = True
                        .ToolStripImport.Enabled = False
                        .ToolStripPrint.Enabled = True
                        .ToolStripFilter.Enabled = True
                        .ToolStripCheck.Enabled = False
                        .ToolStripComplete.Enabled = False
                        .ToolStripUnCheck.Enabled = False
                    End With

                Case ButtonType.Cancel
                    With MainForm
                        .ToolStripAdd.Enabled = True
                        .ToolStripEdit.Enabled = IsFind
                        .ToolStripDelete.Enabled = IsFind
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = IsFind
                        .ToolStripLast.Enabled = IsFind
                        .ToolStripNext.Enabled = IsFind
                        .ToolStripPrivous.Enabled = IsFind
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

                Case ButtonType.Edit
                    With MainForm
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = False
                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = True
                        .ToolStripCancel.Enabled = True
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

            End Select
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

#End Region

#End Region

#Region "Events"

    Private Sub Frm_CSPrintMonthCount_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.fLoadBool = False
        Me.dtp_start_1.Text = Format(CType(ServerDate, Date), "yyyy-MM-01")
        Me.dtp_end_1.Text = ServerDate
        Me.dtp_start_2.Text = Format(CType(ServerDate, Date), "yyyy-MM-01")
        Me.dtp_end_2.Text = ServerDate
        FillComboxForEnum(Me.cbxfLevel, GetType(ModEnum.ComplainLevel))
        Me.cbxfLevel.Text = ModEnum.ComplainLevel.嚴重.ToString()
        Me.fLoadBool = True
    End Sub

    Private Sub btnFind_1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFind_1.Click
        ExecFind()
    End Sub

    Private Sub btnFind_2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFind_2.Click
        ExecFind_2()
    End Sub

    Private Sub DataGridView1_RowPostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DataGridView1.RowPostPaint
        Try
            Dim Grid As DataGridView = DirectCast(sender, DataGridView)
            Dim SBrush As New SolidBrush(Grid.RowHeadersDefaultCellStyle.ForeColor)
            e.Graphics.DrawString(Convert.ToString(e.RowIndex + 1, System.Globalization.CultureInfo.CurrentCulture), e.InheritedRowStyle.Font, SBrush, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4)
            SBrush = Nothing
        Catch ex As Exception
            MessageBox.Show("DGV_Master_RowPostPaint:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub DataGridView2_RowPostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DataGridView2.RowPostPaint
        Try
            Dim Grid As DataGridView = DirectCast(sender, DataGridView)
            Dim SBrush As New SolidBrush(Grid.RowHeadersDefaultCellStyle.ForeColor)
            e.Graphics.DrawString(Convert.ToString(e.RowIndex + 1, System.Globalization.CultureInfo.CurrentCulture), e.InheritedRowStyle.Font, SBrush, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4)
            SBrush = Nothing
        Catch ex As Exception
            MessageBox.Show("DGV_Master_RowPostPaint:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#End Region

#Region "Interface"

    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd
        SelectObject.ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel

    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete

    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit

    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport
        Try
            Me.Cursor = Cursors.WaitCursor

            Select Case Me.TabControl1.SelectedIndex
                Case 0
                    If Me.DataGridView1.Rows.Count <= 0 Then
                        Return True
                    End If

                    Dim Grid As DataGridView = Me.DataGridView1
                    Dim ds As New DataSet
                    Dim Dtab As DataTable
                    Dtab = DirectCast(Grid.DataSource, DataTable).Copy
                    Dtab.TableName = "Receive"
                    Dim Hash As New Hashtable
                    RemoveHideColumn(Grid, Dtab)
                    Dim export As New ExcelExport()
                    Dim dw As Int16 = DatePart(DateInterval.Month, Me.dtp_end_1.Value)
                    export.ExprotToExcel_PrintMonthCount(Dtab, dw.ToString & "月每日來電統計表")

                Case 1
                    If Me.DataGridView2.Rows.Count <= 0 Then
                        Return True
                    End If

                    Dim Grid As DataGridView = Me.DataGridView2
                    Dim ds As New DataSet
                    Dim Dtab As DataTable
                    Dtab = DirectCast(Grid.DataSource, DataTable).Copy
                    Dtab.TableName = "Receive"
                    Dim Hash As New Hashtable
                    RemoveHideColumn(Grid, Dtab)
                    Dim export As New ExcelExport()
                    Dim dw As Int16 = DatePart(DateInterval.Month, Me.dtp_end_1.Value)
                    export.ExprotToExcel(Dtab, dw.ToString & "月每日投訴統計表")

            End Select

        Catch ex As Exception
            MessageBox.Show(ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            Me.Cursor = Cursors.Default
        End Try

    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter

    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst

    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast

    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext

    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious

    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize

    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint

    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave

    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect

    End Function

#End Region

    Public Function UnionDataTable(ByVal dt1 As DataTable, ByVal dt2 As DataTable) As DataTable
        Dim NameCol As String = String.Empty
        If Me.TabControl1.SelectedIndex = 0 Then
            NameCol = "姓 名 "
        Else
            If dt1.Columns(0).ColumnName.Equals("ListenPsn", StringComparison.InvariantCultureIgnoreCase) Then
                dt1.AcceptChanges()
                dt1 = dt1.Copy()
                dt1.Columns("ListenPsn").ColumnName = "姓名"
            End If
            NameCol = "姓名"
        End If

        If dt1.Columns.Contains("fTotals") Then
            dt1.Columns.Remove("fTotals")
        End If
        If dt1.Columns.Contains("fAverage") Then
            dt1.Columns.Remove("fAverage")
        End If
        If dt1.Columns.Contains("fDays") Then
            dt1.Columns.Remove("fDays")
        End If
        If dt1.Columns.Contains("來電總數") Then
            dt1.Columns.Remove("來電總數")
        End If
        If dt1.Columns.Contains("平均每天處理來電總數") Then
            dt1.Columns.Remove("平均每天處理來電總數")
        End If
        If dt1.Columns.Contains("總天數") Then
            dt1.Columns.Remove("總天數")
        End If
        If dt2.Columns.Contains("來電總數") Then
            dt2.Columns.Remove("來電總數")
        End If
        If dt2.Columns.Contains("平均每天處理來電總數") Then
            dt2.Columns.Remove("平均每天處理來電總數")
        End If
        If dt2.Columns.Contains("總天數") Then
            dt2.Columns.Remove("總天數")
        End If
        If dt2.Columns.Contains("投訴總數") Then
            dt2.Columns.Remove("投訴總數")
        End If
        If dt2.Columns.Contains("平均每天處理投訴總數") Then
            dt2.Columns.Remove("平均每天處理投訴總數")
        End If
        dt1.AcceptChanges()
        dt2.AcceptChanges()

        Dim rDt As DataTable = dt1.Clone

        ' "姓 名 "

        For Each col As DataColumn In dt2.Columns
            If Not rDt.Columns.Contains(col.ColumnName) Then
                rDt.Columns.Add(col.ColumnName, col.DataType)
            End If
        Next

        rDt.Columns(NameCol).SetOrdinal(0)

        For I As Integer = 1 To rDt.Columns.Count - 1
            rDt.Columns(I).DataType = GetType(Double)
        Next
        rDt.AcceptChanges()


        '所有在dt1中存在的記錄添加到新表中，如果dt2中存在同樣的記錄行，那么對數據進行合并
        For Each row1 As DataRow In dt1.Rows
            Dim row As DataRow = rDt.NewRow()

            '使用dt1的數據給新行（row）賦值
            For Each col As DataColumn In rDt.Columns
                Dim colName As String = col.ColumnName
                If dt1.Columns.Contains(colName) Then
                    If colName.Equals(NameCol, StringComparison.InvariantCultureIgnoreCase) Then
                        row(colName) = row1(colName).ToString
                    Else
                        row(colName) = Val(row(colName).ToString) + Val(row1(colName).ToString)

                    End If
                End If
            Next

            '如果dt2中同時也存在該行，那么將該行的數據合并到新行
            Dim rows2() As DataRow = dt2.Select("[" + NameCol + "]='" + row1(NameCol).ToString + "'")
            If rows2.Length > 0 Then
                For Each col As DataColumn In rDt.Columns
                    Dim colName As String = col.ColumnName
                    If dt2.Columns.Contains(colName) Then
                        If colName.Equals(NameCol, StringComparison.InvariantCultureIgnoreCase) Then
                            row(colName) = row1(colName).ToString
                        Else
                            row(colName) = Val(row(colName).ToString) + Val(rows2(0)(colName).ToString)
                        End If
                    End If
                Next
            End If
            rDt.Rows.Add(row)

        Next

        '還有一部分數據沒有出現在dt1中，只出現在dt2中，那么也需要將它添加到新表中
        For Each row2 As DataRow In dt2.Rows
            Dim rows() As DataRow = rDt.Select("[" + NameCol + "]='" + row2(NameCol).ToString + "'")
            If rows.Length = 0 Then
                Dim row As DataRow = rDt.NewRow()

                '使用dt2的數據給新行（row）賦值
                For Each col As DataColumn In dt2.Columns
                    Dim colName As String = col.ColumnName
                    If dt2.Columns.Contains(colName) Then
                        If colName.Equals(NameCol, StringComparison.InvariantCultureIgnoreCase) Then
                            row(colName) = row2(colName).ToString
                        Else
                            row(colName) = Val(row2(colName).ToString)
                        End If
                    End If
                Next
                rDt.Rows.Add(row)
            End If
        Next
        rDt.Columns.Add("fTotals", GetType(System.Double))
        rDt.Columns.Add("fDays", GetType(System.Int32))
        rDt.Columns.Add("fAverage", GetType(System.Double))
        ComputeDataTable(rDt)

        rDt.AcceptChanges()
        Return rDt
    End Function


    Private Sub btnImportAndMerge_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImportAndMerge.Click, btnImportAndMerge1.Click
        Dim dt As DataTable
        If sender.Equals(btnImportAndMerge) Then
            If Not TypeOf Me.DataGridView1.DataSource Is DataTable Then
                Exit Sub
            End If

            dt = CType(Me.DataGridView1.DataSource, DataTable)
        Else
            If Not TypeOf Me.DataGridView2.DataSource Is DataTable Then
                Exit Sub
            End If
            dt = CType(Me.DataGridView2.DataSource, DataTable)
        End If

        Dim ImportForm As New Frm_ImportExcel
        Dim ds As DataSet
        If ImportForm.ShowDialog() = DialogResult.OK Then
            ds = ImportForm.Ds
        Else
            Exit Sub
        End If
        If ds Is Nothing OrElse ds.Tables Is Nothing OrElse ds.Tables(0) Is Nothing OrElse ds.Tables(0).Columns.Count < 3 OrElse Not (ds.Tables(0).Columns(0).ColumnName.Equals("姓 名 ", StringComparison.InvariantCultureIgnoreCase) _
        OrElse ds.Tables(0).Columns(0).ColumnName.Equals("姓名", StringComparison.InvariantCultureIgnoreCase)) Then
        Else
            Dim dta As DataTable = Me.UnionDataTable(dt, ds.Tables(0))
            dta.AcceptChanges()
            If sender.Equals(Me.btnImportAndMerge) Then
                dta.Columns("fTotals").ColumnName = "來電總數"
                dta.Columns("fDays").ColumnName = "總天數"
                dta.Columns("fAverage").ColumnName = "平均每天處理來電總數"
                dta.AcceptChanges()
                Me.DataGridView1.DataSource = dta
            Else
                Me.DataGridView2.DataSource = dta
                BindDataGridViewCaption_1(Me.DataGridView2, Me.ReturnCaption(1))
                Me.DataGridView2.Select()
                Me.DataGridView2.Columns("姓名").DisplayIndex = 0
                Dim count As Int32 = Me.DataGridView2.Columns.Count

                Me.DataGridView2.Columns("fAverage").DisplayIndex = count - 1
                Me.DataGridView2.Columns("fDays").DisplayIndex = count - 2
                Me.DataGridView2.Columns("fTotals").DisplayIndex = count - 3
                Me.DataGridView2.Update()
                Me.DataGridView2.Refresh()
            End If
        End If
    End Sub
End Class

